package blockencryption;

import general.Utility;

import javax.crypto.BadPaddingException;

import org.eclipse.swt.graphics.ImageData;

import ui.ImageDisplayer;

public class CipherManager {
	private final ImageDisplayer imageDisplayer;
	private int timesEncrypted = 0;
	private final int[][] currentData;

	public CipherManager(ImageDisplayer imageDisplayer, ImageData imageData) {
		this.imageDisplayer = imageDisplayer;
		currentData = new int[imageData.height][];
		for (int lineNo = 0; lineNo < imageData.height; lineNo++) {
			currentData[lineNo] = new int[imageData.width];
			imageData.getPixels(0, lineNo, imageData.width, currentData[lineNo], 0);
		}
	}

	public void cipher(boolean encrypt) {
		byte[] key = retrieveKey();
		try {
			for (int lineNo = 0; lineNo < currentData.length; lineNo++) {
				currentData[lineNo] = BlockCipherer.blockCipher(key, currentData[lineNo], encrypt);
			}
			if (encrypt) {
				timesEncrypted++;
			} else {
				timesEncrypted--;
			}
			imageDisplayer.setDecryptEnabled(timesEncrypted != 0);
			imageDisplayer.setImageData(currentData);
			imageDisplayer.setStatus("");
		} catch (BadPaddingException except) {
			imageDisplayer.setStatus("Wrong key!");
		}
	}

	private byte[] retrieveKey() {
		String keyString = imageDisplayer.getKey();
		byte[] key = Utility.hexToBytes(keyString);
		if (key.length == 0) {
			key = Encryptor.generateKey();
			imageDisplayer.setKey(Utility.bytesToHex(key));
		}
		return key;
	}
}